<?php

namespace app\controllers\admin\uni\merchant;

use app\controllers\admin\base\AdminController;
use app\models\merchant\Merchant as Model;
use app\models\merchant\MerchantImage;
use app\redis\Cache;

/**
 * Class MerchantController
 * @package app\controllers\admin\uni\merchant
 */
class MerchantController extends AdminController
{
    public function actionList()
    {
        $name = $this->post('name');
        $nickname = $this->post('nickname');
        $mobile = $this->post('mobile');

        $id = $this->post('id');
        $user_id = $this->post('user_id');

        $type = $this->post('type');

        $status = $this->post('status');
        $export = $this->post('export');

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');

        $query = Model::find()
            ->where(['!=', 'status', Model::$statusMapping['DELETE']])
            ->with(['image']);

        if ($status > Model::$statusMapping['ALL']) {
            $query->andWhere(['status' => $status]);
        }

        if ($sort) {
            $prop = substr($sort, 0, 1);
            $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
            $order = substr($sort, 1);
            $query->orderBy([$order => $prop]);
        } else {
            $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC]);
        }

        if ($type) {
            $query->andWhere(['type' => $type]);
        }

        if ($id) {
            $query->andWhere(['id' => $id]);
        }
        if ($user_id) {
            $query->andWhere(['user_id' => $user_id]);
        }
        if ($name) {
            $query->andWhere(['like', 'name', $name]);
        }
        if ($nickname) {
            $query->andWhere(['like', 'nickname', $nickname]);
        }
        if ($mobile) {
            $query->andWhere(['like', 'mobile', $mobile]);
        }

        // export
        if ($export) {
            $list = $query->with(['type0'])
                ->asArray()
                ->all();
            return $this->success($list);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->with(['type0'])
            ->asArray()
            ->all();

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }

    public function actionEdit()
    {
        $data = $this->post();

        try {
            if (isset($data['id']) && $data['id'] > 0) {
                $model = Model::findOne(['id' => $data['id']]);
                if (!$model) {
                    return $this->fail('操作失败');
                }

            } else {
                $model = new Model();
                $model->status = 0;
            }
            $data = ['Merchant' => $data];
            if ($model->load($data) && $model->save()) {

                // clear cache
                Cache::deleteAll(Cache::$MERCHANT);

                return $this->success($model, '操作成功');
            }
            // var_dump($model->getFirstErrors());exit;
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionView()
    {
        $id = $this->post('id');
        $model = Model::find()
            ->where(['id' => $id])
            ->with(['image'])
            ->asArray()
            ->one();

        if ($model) {
            return $this->success($model);
        }

        return $this->fail('不存在该商家');
    }

    public function actionRemove()
    {
        $id = $this->post('id');

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = Model::$statusMapping['DELETE'];
            $model->save();
            return $this->success($model, '删除成功');
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionStatusList()
    {
        return $this->success(Model::statusList());
    }

    // public function actionChangeStatus()
    // {
    //     $id = intval($this->post('id'));
    //     $status = intval($this->post('status'));
    //
    //     try {
    //         $model = Model::findOne(['id' => $id]);
    //         $model->status = $status;
    //         $model->save();
    //
    //         return $this->success();
    //     } catch (\Exception $e) {
    //         return $this->fail('操作错误: ' . $e->getMessage());
    //     }
    // }

    public function actionPass()
    {
        $id = intval($this->post('id'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = Model::$statusMapping['OK'];
            $model->save();

            // clear cache
            Cache::deleteAll(Cache::$MERCHANT);

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionReject()
    {
        $id = intval($this->post('id'));
        $reject = $this->post('reject');

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = Model::$statusMapping['REJECT'];
            $model->reject = $reject;
            $model->save();
            return $this->success();
        } catch (\Exception $e) {
            return $this->fail();
        }
    }

    public function actionCancel()
    {
        $id = intval($this->post('id'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = Model::$statusMapping['CANCEL'];
            $model->save();
            return $this->success();
        } catch (\Exception $e) {
            return $this->fail();
        }
    }

    public function actionChangeSort()
    {
        $id = intval($this->post('id'));
        $sort = intval($this->post('sort'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->sort = $sort;
            $model->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('操作错误: ' . $e->getMessage());
        }
    }

    public function actionBatchRemove()
    {
        $ids = $this->post('ids');

        try {
            Model::updateAll(['status' => Model::$statusMapping['DELETE']], ['id' => $ids]);

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('删除错误: ' . $e->getMessage());
        }
    }

    // view image
    public function actionViewImage()
    {
        $id = $this->post('id');

        $list = MerchantImage::find()
            ->where(['merchant_id' => $id])
            ->with(['image'])
            ->orderBy(['type' => SORT_ASC, 'id' => SORT_ASC])
            ->asArray()
            ->all();

        return $this->success($list);
    }
}